package com.tanhua.dubbo.api.impl.mongo;

import com.tanhua.domain.mongo.UserLocation;
import com.tanhua.domain.vo.UserLocationVo;
import com.tanhua.dubbo.api.mongo.UserLocationApi;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;


@Service(timeout = 200000)
public class UserLocationApiImpl implements UserLocationApi {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    public void saveLocation(
            Long userId, Double latitude, Double longitude, String addrStr) {
        // 保存用户地理位置 分2步：
        // 1. 根据登陆用户的id查询user_location表，如果不存在，插入一条数据
        Query query = new Query(Criteria.where("userId").is(userId));
        if (!mongoTemplate.exists(query, UserLocation.class)) {
            UserLocation userLocation = new UserLocation();
            userLocation.setUserId(userId);
            userLocation.setLocation(new GeoJsonPoint(longitude,latitude));
            userLocation.setAddress(addrStr);
            userLocation.setCreated(System.currentTimeMillis());
            userLocation.setUpdated(System.currentTimeMillis());
            userLocation.setLastUpdated(System.currentTimeMillis());
            // 新增一条记录
            mongoTemplate.insert(userLocation);
        } else {
            // 2. 如果已经存在，执行更新
            Update update = new Update();
            update.set("address",addrStr);
            update.set("location",new GeoJsonPoint(longitude,latitude));
            update.set("updated",System.currentTimeMillis());
            update.set("lastUpdated",System.currentTimeMillis());
            mongoTemplate.updateFirst(query,update,UserLocation.class);
        }
    }

    @Override
    public List<UserLocationVo> searchNear(Long userId, Long distance) {
        // 1.根据用户id查询，获取登陆用户的坐标
        Query query = new Query(Criteria.where("userId").is(userId));
        UserLocation userLocation = mongoTemplate.findOne(query, UserLocation.class);
        // 2.获取用户的坐标
        GeoJsonPoint location = userLocation.getLocation();

        // 3.搜附近
        // 3.1 创建Distance举例对象，以这个举例作为半径画圆
        Distance d = new Distance(distance/1000, Metrics.KILOMETERS);
        // 3.2 创建Circle对象, location作为圆点（用户坐标）
        Circle circle = new Circle(location,d);
        // 3.3 搜附近
        query = new Query(
                Criteria.where("location").withinSphere(circle)
        );
        List<UserLocation> list = mongoTemplate.find(query, UserLocation.class);
        return UserLocationVo.formatToList(list);
    }
}

















